package com.yuwei.home.model

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.yuwei.common.entity.Res
import com.yuwei.common.entity.SimpleVideoEntity
import com.yuwei.common.entity.SimpleVideoEntityItem
import com.yuwei.home.HomeApiService
import com.yuwei.http.OkHttpClientManager.createRetrofit

class HomePagingSource constructor(private val typeId : String,private val pageSize : Int = 5): PagingSource<Int, SimpleVideoEntityItem>() {
    private val apiService = createRetrofit().create(HomeApiService::class.java)
    override fun getRefreshKey(state: PagingState<Int, SimpleVideoEntityItem>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1)?:anchorPage?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, SimpleVideoEntityItem> {
        try {
            val pageIndex = params.key?:1
            val loadSize = params.loadSize

            var response : Res<SimpleVideoEntity> = apiService.getSimpleVideoByChannelIdPaging(typeId,pageIndex,pageSize)
            val prePageKey: Int ?= (pageIndex-1).run {
                if(this == 0) null else this
            }
            val nextPageKey: Int? = when{
                loadSize > pageSize-> loadSize/pageSize+1
                response.code == 200 -> pageIndex+1
                else -> null
            }
            return LoadResult.Page(response.data,prePageKey,nextPageKey)
        }catch (e : Exception){
            e.printStackTrace()
            return LoadResult.Error(e)
        }
    }

}